﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SocialLotus.DAO;
using System.Reflection;
using System.Diagnostics;

namespace SocialLotus.BL
{
    public class BLSession : IDisposable
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="BLSession"/> class.
        /// </summary>
        public BLSession()
        {
            DAOSession = new DAOSession();
            Debug.WriteLine("BLSession created");

        }

        /// <summary>
        /// Gets or sets the DAO session.
        /// </summary>
        /// <value>The DAO session.</value>
        internal DAOSession DAOSession
        {
            get;
            set;
        }

        public T GetBL<T>() where T : BaseBL
        {
            //cache created objects?
            return typeof(T).InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, new object[] { DAOSession }) as T;
        }



        #region IDisposable Members

        /// <summary>
        /// Disposes of the wrapped DAOSession.
        /// </summary>
        public void Dispose()
        {
            Debug.WriteLine("BLSession dispose");

            if (DAOSession != null)
            {
                DAOSession.Dispose();
            }
        }

        #endregion

        public void ClearChanges()
        {

            if (DAOSession != null)
            {
                DAOSession.ClearChanges();
            }
        }

        public static void CreateDatabase()
        {
            DAOFactory.CreateDatabaseSchema(DAOFactory.CreationType.Create);
        }

        public static void DropAndCreateDatabase()
        {
            DAOFactory.CreateDatabaseSchema(DAOFactory.CreationType.DropAndCreate);
        }

        public static void UpdateDatabase()
        {
            DAOFactory.CreateDatabaseSchema(DAOFactory.CreationType.Update);
        }
    }
}
